package pl.easyshop.core.common.selectable.helper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import pl.easyshop.core.common.selectable.SimpleSelectableItem;

/**
 * Helper object for create selectable enums list.
 * 
 * @author Pawel Witkowski
 *
 * @param <E> enum typed
 */
public class SelectableEnumHelper<E extends Enum<E>> implements Serializable {
	
	/** Unique serialization identifier. */
	private static final long serialVersionUID = -4871445052106113830L;

	/** Items on list. */ 
	private List<SimpleSelectableItem<String, E>> items = new ArrayList<SimpleSelectableItem<String,E>>();
	
	/** Selected index on list. */
	private int selectedIndex;
	
	/** Selected list value. */
	private E selectedValue;
	
	/**
	 * Constructor.
	 * 
	 * @param enumClazz
	 * @param messagePrefix
	 */
	public SelectableEnumHelper (Class<E> enumClazz, String messagePrefix) {
		E[] enu = enumClazz.getEnumConstants();
		for (E enumElement : enu) {
			items.add(new SimpleSelectableItem<String, E>(enumElement.name(), enumElement, messagePrefix + enumElement.name()));
		}
	}

	/**
	 * @param selection
	 * @return
	 */
	public SelectableEnumHelper<E> withSelectedValue(E selection) {
		if (selection == null) {
			selectedIndex = 0;
		} else {
			for (int index = 0; index < items.size(); index++) {
				SimpleSelectableItem<String, E> item = items.get(index);
				if(item.getItemValue() == selection) {
					this.selectedIndex = index;
					this.selectedValue = selection;
					break;
				}
			}
		}
		return this;
	}

	public List<SimpleSelectableItem<String, E>> getItems() {
		return items;
	}
	
	/**
	 * Get selectedIndex property value.
	 * @return the selectedIndex
	 */
	public int getSelectedIndex() {
		return selectedIndex;
	}

	/**
	 * Set selectedIndex property value.
	 * @param selectedIndex the selectedIndex to set
	 */
	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
		selectedValue = items.get(selectedIndex).getItemValue();
	}
	
	/**
	 * Get selectedValue property value.
	 * @return the selectedValue
	 */
	public E getSelectedValue() {
		return selectedValue;
	}
	
	/**
	 * Set selectedValue property value.
	 * @param selectedValue the selectedValue to set
	 */
	public void setSelectedValue(E selectedValue) {
		this.selectedValue = selectedValue;
	}

	/*public SelectionControl sort() {
		Collections.sort(items);
		withSelection(initialSelection);
		return this;
	}*/

	/*public SelectionControl sort(Comparator comparator) {
		Collections.sort(items, comparator);
		withSelection(initialSelection);
		return this;
	}
*/
	/*public SelectionControl reverse() {
		Collections.reverse(items);
		withSelection(initialSelection);
		return this;
	}*/

}